package cn.mrx.eas.controller;

import cn.mrx.eas.server.ResponseCode;
import cn.mrx.eas.server.ServerResponse;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Author: Mr.X
 * Date: 2018/1/8 上午11:09
 * Description:
 */
@Slf4j
@Controller
@RequestMapping
public class SysLoginController {

    @Autowired
    private Producer captchaProducer;

    // 登录页面
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    // 验证码
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0); // 禁止服务器端缓存
        response.setHeader("Cache-Control", "no-store, no-cache"); // 设置标准的HTTP/1.1 no-cache headers
        response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // 设置IE扩展的HTTP/1.1 no-cache headers(use addHeader)
        response.setHeader("Pragma", "no-cache"); // 设置标准的HTTP/1.0,不缓存图片
        response.setContentType("image/jpeg"); // 返回一个jpeg图片,默认是text/html(输出文档的MIMI类型)
        String text = captchaProducer.createText();
        log.info("系统生成验证码为:{}", text);
        SecurityUtils.getSubject().getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        BufferedImage image = captchaProducer.createImage(text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

    // 登录逻辑
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse login(String username, String password, String captcha, Integer rememberMe) {
        // 校验参数
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(captcha)) {
            return ServerResponse.error(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getMsg());
        }
        try {
            // 校验验证码
            String sessionCaptcha = (String) SecurityUtils.getSubject().getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (!StringUtils.equalsIgnoreCase(captcha, sessionCaptcha)) {
                return ServerResponse.error("验证码错误");
            }
            // 登录
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            // 记住我
            token.setRememberMe(rememberMe == null ? false : (rememberMe == 0 ? true : false));
            subject.login(token);
        } catch (UnknownAccountException e) {
            return ServerResponse.error("账号不存在");
        } catch (IncorrectCredentialsException e) {
            return ServerResponse.error("账号或密码错误");
        }
        return ServerResponse.success("登录成功");
    }
}